# -*- coding: utf-8 -*-
#*******************************************************************************
#   
#   http://www.bbhou.com/manhua/comic_name/ 解析器
#
#*******************************************************************************
from base import *

tag='bbhou'

#---------------------------- 验证模块 ----------------------------

def url_judgement(url):
    if re.match(r'http://www.bbhou.com/manhua/[\w\d_]+/',url):
        return valid_check(url)
    return False

def valid_check(url):
    print('{} catch {}'.format(tag,url))
    content=request_for(url,common_headers);
    if content:
        return get_loader(url)
    return False

def get_loader(url):
    return BbhouLoader(url,BbhouPageParser,BbhouVolParser)

#---------------------------- 下载器 ----------------------------

class BbhouLoader(ComicLoader):
    def __init__(self,url,comic_page_parser,comic_vol_parser):
        super().__init__(url,comic_page_parser,comic_vol_parser)

#---------------------------- 解析器 ----------------------------

class BbhouPageParser(ComicPageParser):
    def __init__(self,comic):
        super().__init__(comic)
    def work(self,content):
        # title
        self.comic.titlere.compile(r'<h1>(.*?)</h1>',re.S|re.M).findall(content)[0].strip()
        # description
        des_content=re.compile(r'"display:none"><span>(.*?)br',re.S|re.M).findall(content)[0].strip()
        self.comic.description=re.compile(r'</a>(.*?)<',re.S|re.M).findall(des_content)[0].strip()
        # cover
        self.comic.cover=re.compile(r'<meta property="og:image" content="(.*?)"',re.S|re.M).findall(content)[0]
        # vols
        vols_content=re.compile(r'<div class="section-list all">(.*?)</div><!--',re.S|re.M).findall(content)
        if len(vols_content)==0:
            vols_content=re.compile(r'</h6><span class="hover">(.*?)</div><!--',re.S|re.M).findall(content)
        self.feed(vols_content[0])
    def handle_starttag(self,tag,attrs):
        site_preifx='http://www.bbhou.com'
        if tag=='a':
            infos={}
            for (v,k) in attrs:
                infos[v]=k
            self.comic.vols.append(InfoVol(site_preifx+infos['href'],infos['title']))

class BbhouVolParser(ComicVolParser):
    def __init__(self):
        super().__init__()
    def work(self,content):
        pics=re.compile(r'var picTree = \[(.*?)\];',re.S|re.M).findall(content)[0].replace('\\','').replace('"','').split(',')
        pic_base=re.compile(r"var pic_base = '(.*?)';").findall(content)[0]
        for pic in pics:
            self.pic_urls.append((pic_base+pic,zero_prefix(self.pic_index)))
            self.pic_index+=1